package gui;

import java.awt.GridLayout;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import dbConnection.Database;

public class ResultsPanel extends JPanel {
    /**
     * 
     */
    private static final long serialVersionUID = -7179438277377351239L;
    public Database DB;
    private JTable table;
    public ResultsPanel(Database DB) {
	this.DB = DB;
	setLayout(new GridLayout(1,1));
    }
    
    /** runs provided string as sql query, returns error if one is caught, otherwise generic success message */
    public String sqlQuery(String query) {
	ResultSet rs = null;
	//JPanel panel = new JPanel();
	try {
	    rs = DB.con.prepareStatement(query).executeQuery();
	    ResultSetMetaData meta = rs.getMetaData();
	    Vector<String> columnNames = new Vector<String>();
	    
	    //get column names
	    int columnCount = meta.getColumnCount();
	    for (int i = 1; i <= columnCount; i++) {
		columnNames.add(meta.getColumnName(i));
	    }
	    //get table datda
	    Vector<Vector<Object>> data = new Vector<Vector<Object>>();
	    while (rs.next()) {
		Vector<Object> vector = new Vector<Object>();
		for(int i = 1; i<= columnCount; i++) {
		    vector.add(rs.getObject(i));
		}
		data.add(vector);
	    }
	    removeAll(); //remove current jtable, if it exists
	    DefaultTableModel tm = new DefaultTableModel(data, columnNames);
	    table = new JTable(tm);
	    table.setFillsViewportHeight(true);
	    TableColumnAdjuster adjuster = new TableColumnAdjuster(table);//dynamically resize column widths
	    adjuster.adjustColumns();
	    add(new JScrollPane(table));
	    
	    revalidate();
	} catch (SQLException e) {
	    //e.printStackTrace();
	    return e.toString();
	}
	return "Query Successful";
    }
    
    /** executes the provided string as a sql update, returning sql error if one is caught */
    public String sqlUpdate(String update) {
	try{
	    DB.con.prepareStatement(update).executeUpdate();
	} catch (SQLException e) {
	    //e.printStackTrace();
	    return e.toString();
	}
	return "Update Successful";
    }
}
